package com.citywithincity.redis.utils.impl;

import java.lang.reflect.Field;

import com.citywithincity.db.interfaces.IValueConvert;
import com.citywithincity.redis.utils.RedisField;

public class RedisFieldImpl implements RedisField {

	private Field field;
	private IValueConvert toStringConvert;
	private IValueConvert toValueConvert;
	
	public RedisFieldImpl(Field field, IValueConvert toStringConvert,IValueConvert toValueConvert) {
		this.field = field;
		this.toStringConvert = toStringConvert;
		this.toValueConvert = toValueConvert;
	}
	
	@Override
	public String get(Object data) {
		
		try {
			Object value = field.get(data);
			if(toStringConvert!=null){
				return (String) toStringConvert.convert(value);
			}
			if(value==null)return null;
			return String.valueOf(value);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public void set(Object data, String value) {
		Object realValue;
		if(toValueConvert!=null){
			realValue = toValueConvert.convert(value);
		}else{
			realValue = value;
		}
		try {
			field.set(data, realValue);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String getName() {
		return field.getName();
	}

}
